package com.industrial.premu.service.impl.sqsj;

import java.io.InputStream;
import java.util.*;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.uuid.IdUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.PreMuReject;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportVeto;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.PreMuRejectMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportVetoMapper;
import com.industrial.premu.service.IPreMuImportVetoService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 亩产导入数据-否决项Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-27
 */
@Service
public class PreMuImportVetoServiceImpl implements IPreMuImportVetoService
{
    @Autowired
    private PreMuImportVetoMapper preMuImportVetoMapper;

    @Autowired
    private PreMuRejectMapper preMuRejectMapper;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;



    private static final int BATCH_SIZE = 300;

    /**
     * 查询亩产导入数据-否决项
     *
     * @param id 亩产导入数据-否决项主键
     * @return 亩产导入数据-否决项
     */
    @Override
    public PreMuImportVeto selectPreMuImportVetoById(String id)
    {
        return preMuImportVetoMapper.selectPreMuImportVetoById(id);
    }

    /**
     * 查询亩产导入数据-否决项列表
     *
     * @param preMuImportVeto 亩产导入数据-否决项
     * @return 亩产导入数据-否决项
     */
    @Override
    public List<PreMuImportVeto> selectPreMuImportVetoList(PreMuImportVeto preMuImportVeto)
    {
        return preMuImportVetoMapper.selectPreMuImportVetoList(preMuImportVeto);
    }

    /**
     * 新增亩产导入数据-否决项
     *
     * @param preMuImportVeto 亩产导入数据-否决项
     * @return 结果
     */
    @Override
    public int insertPreMuImportVeto(PreMuImportVeto preMuImportVeto)
    {
        return preMuImportVetoMapper.insertPreMuImportVeto(preMuImportVeto);
    }

    /**
     * 修改亩产导入数据-否决项
     *
     * @param preMuImportVeto 亩产导入数据-否决项
     * @return 结果
     */
    @Override
    public int updatePreMuImportVeto(PreMuImportVeto preMuImportVeto)
    {
        return preMuImportVetoMapper.updatePreMuImportVeto(preMuImportVeto);
    }

    /**
     * 批量删除亩产导入数据-否决项
     *
     * @param ids 需要删除的亩产导入数据-否决项主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportVetoByIds(String[] ids)
    {
        return preMuImportVetoMapper.deletePreMuImportVetoByIds(ids);
    }

    /**
     * 删除亩产导入数据-否决项信息
     *
     * @param id 亩产导入数据-否决项主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportVetoById(String id)
    {
        return preMuImportVetoMapper.deletePreMuImportVetoById(id);
    }

    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeData(PreMuImportVeto preMuImportVeto,String deptCode) {
        preMuImportVetoMapper.removeData(preMuImportVeto);
        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(preMuImportVeto.getYear());
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
    }

    @Override
    public AjaxResult importRejectData(String year, String s, InputStream inputStream) {
        int successNum = 0;
        int updateNum = 0;
        PreMuImportVeto preMuImportVeto = new PreMuImportVeto();
        try{
            Workbook wb = WorkbookFactory.create(inputStream);
            if(wb!= null) {
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    Row headerRow = sheet.getRow(0);
                    Row headerNameRow = sheet.getRow(1);
                    //全部id
                    List<PreMuReject> asiDOs = new ArrayList<>();
                    int colSum = 0; //列长
                    int rowNum = sheet.getPhysicalNumberOfRows(); //行长
                    PreMuReject queryParams = new PreMuReject();
                    if (headerRow != null && headerNameRow != null) {
                        queryParams.setYears(year);
                        queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                        List<PreMuReject> colCalssList = preMuRejectMapper.selectPreMuRejectList(queryParams);
                        colSum = headerRow.getPhysicalNumberOfCells(); //列长
                        //判断是否设置了加减分项
                        if (colCalssList == null || colCalssList.size() <= 0) {
                            Map<String,String> resultMap = new HashMap<>();
                            resultMap.put("allMsg","系统中未设定对应所选年份的否决项，请先设定再导入！");
                            return AjaxResult.error("导入失败",resultMap);
                        }
                        //判断模板是否过期
                        for (int i = 2; i < colSum; i++) {
                            Cell idCell = headerRow.getCell(i);
                            String idSign = idCell.getStringCellValue().replace(" ", "");
                            int sign = 1;
                            for (PreMuReject asiDO : colCalssList) {
                                if (idSign.equals(asiDO.getId())) {
                                    asiDOs.add(asiDO);
                                    break;
                                }
                                if (sign == colCalssList.size()) {
                                    Map<String,String> resultMap = new HashMap<>();
                                    resultMap.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                                    return AjaxResult.error("导入失败",resultMap);
                                }
                                sign++;
                            }
                        }
                    }
                    preMuImportVeto.setCompanyType(s);
                    preMuImportVeto.setYear(year);
                    preMuImportVeto.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());

                    //批处理用
                    Map<String, Object> existMap = new HashMap<String, Object>();
                    List<String> usccList = new ArrayList<String>();
                    List<PreMuImportVeto> existList = new ArrayList<PreMuImportVeto>();
                    List<PreMuImportVeto> addImportList = new ArrayList<PreMuImportVeto>();
                    List<PreMuImportVeto> updateImportList = new ArrayList<PreMuImportVeto>();

                    //查询企业信息
                    PreMuCompanyInfo companyInfoParams = new PreMuCompanyInfo();
                    companyInfoParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                    List<PreMuCompanyInfo> comList = preMuCompanyInfoMapper.selectPreMuCompanyInfoList(companyInfoParams);
                    if(comList != null && !comList.isEmpty()){
                        comList.forEach(com ->{
                            if(com.getUscc() != null && !"".equals(com.getUscc())) {
                                usccList.add(com.getUscc().trim());
                            }
                        });
                    }


                    PreMuImportVeto importVeto = new PreMuImportVeto();
                    importVeto.setYear(year);
                    importVeto.setCompanyType(s);
                    importVeto.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                    existList = preMuImportVetoMapper.getImportExistList(importVeto);

                    String oldUscc = "";
                    Map<String, Object> itemIdMap = new HashMap<String, Object>();
                    if(existList != null && !existList.isEmpty()) {
                        for(int i= 0; i<existList.size();i++) {
                            PreMuImportVeto item = existList.get(i);
                            if("".equals(oldUscc)){
                                oldUscc = item.getUscc();
                            }
                            if(!oldUscc.equals(item.getUscc())) {
                                existMap.put(oldUscc, itemIdMap);
                                oldUscc = item.getUscc();
                                itemIdMap = new HashMap<String, Object>();
                            }
                            itemIdMap.put(item.getVetoId(), item.getId());
                        }
                        existMap.put(oldUscc, itemIdMap);
                    }
                    for(int i = 2; i<rowNum;i++){
                        Row rowSign = sheet.getRow(i+0);
                        for(int c= 2; c<colSum;c++){

                            PreMuImportVeto importVetoDODO = new PreMuImportVeto();
                            importVetoDODO.setCompanyType(s);
                            importVetoDODO.setYear(year);
                            importVetoDODO.setCounty(preMuImportVeto.getCounty());
                            Cell companyCell = rowSign.getCell(1);
                            importVetoDODO.setCompanyName(companyCell.getStringCellValue());
                            Cell usccCell = rowSign.getCell(0);
                            importVetoDODO.setUscc(usccCell.getStringCellValue().replace(" ", ""));
                            Cell signCell = rowSign.getCell(c+0);
                            if(signCell!=null&&!"否".equals(signCell.getStringCellValue())&&!"".equals(signCell.getStringCellValue())&&asiDOs!=null&&asiDOs.size()>0){
                                importVetoDODO.setVetoApply(signCell.getStringCellValue());
                                importVetoDODO.setVetoId(asiDOs.get(c-2).getId().replace(" ", ""));
                                importVetoDODO.setVetoName(asiDOs.get(c-2).getRejectName());
                                Map<String, Object> idMap = (Map<String, Object>) existMap.get(importVetoDODO.getUscc());
                                if (idMap != null && idMap.containsKey(importVetoDODO.getVetoId())) {
                                    importVetoDODO.setId((String) idMap.get(importVetoDODO.getVetoId()));
                                    updateImportList.add(importVetoDODO);
                                }else{
                                    importVetoDODO.setId(IdUtils.simpleUUID());
                                    importVetoDODO.setCreateDate(DateUtils.getNowDate());
                                    importVetoDODO.setCreateBy(SecurityUtils.getUserId());
                                    importVetoDODO.setDelFlag("0");
                                    addImportList.add(importVetoDODO);
                                }
                            }
                            if (addImportList != null && addImportList.size() >= BATCH_SIZE) {

                                int importNum = preMuImportVetoMapper.batchSave(addImportList);
                                successNum += importNum;
                                addImportList.clear();
                                System.gc();
                            }
                            if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {

                                int importNum = preMuImportVetoMapper.batchUpdate(updateImportList);
                                successNum += importNum;
                                updateNum += importNum;
                                updateImportList.clear();
                                System.gc();
                            }
                        }
                    }
                    if (addImportList != null && !addImportList.isEmpty()) {

                        int importNum = preMuImportVetoMapper.batchSave(addImportList);
                        successNum += importNum;
                        addImportList.clear();
                        System.gc();
                    }
                    if (updateImportList != null && !updateImportList.isEmpty()) {
                        int importNum = preMuImportVetoMapper.batchUpdate(updateImportList);
                        successNum += importNum;
                        updateNum += importNum;
                        updateImportList.clear();
                        System.gc();
                    }
                }
            }
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg","恭喜您，共"+successNum+"条数据导入成功！");
            resultMap.put("allMsg","恭喜您，共"+successNum+"条数据导入成功！");
            resultMap.put("sum",String.valueOf(successNum));
            resultMap.put("updateNum",String.valueOf(updateNum));
            return AjaxResult.success(resultMap);
        }catch (Exception e){
            String requestURI = "/industrial-premu/importExcelData";
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            e.printStackTrace();
            return AjaxResult.error("数据异常！，请检查您填写的数据");
        }
    }

}